package com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetailUp;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetail.Advice;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetail.CasesDetail;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetail.Quslist;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.TagsGridView;
import com.dididoctor.patient.Ui.TimeWheel.MyDatePicker;
import com.dididoctor.patient.Utils.ABAppUtil;
import com.dididoctor.patient.Utils.ABFileUtil;
import com.dididoctor.patient.Utils.ImageInfo;
import com.dididoctor.patient.Utils.MyToast;
import com.dididoctor.patient.Utils.PhotoHelper;
import com.dididoctor.patient.Utils.PictureGridViewAdapter;
import com.dididoctor.patient.Utils.Util;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： CasesDetailUpActivity
 * @包名称： com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetailUp
 * @创建人： zhanjunjie
 * @创建时间：2016/4/15 16:29
 * @修改人：
 * @修改时间：2016/4/15 16:29
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class CasesDetailUpActivity extends EduActivity implements CasesDetailUpView {

    private EditText mEtHospital, mEtDoctorName, mEtJibing, mEtResult;
    private TextView mTvDate, mTvFinish;

    //医生建议
    private TextView mTvSurvey, mTvMedicine, mTvSee, mTvOther;
    private EditText mEtSurevy, mEtMedicine, mEtSee, mEtOther;
    //    private LinearLayout mLlSurevy, mLlMedicine, mLlSee, mLlOther;
    private TagsGridView mGvImg;


    private String hospital = "", doctorName = "", clinicDate = "", descr = "", result = "", advices = "", pics = "", recId = "", capturePath = "";
    ;
    private boolean issurvey = false, ismedcine = false, issee = false, isother = false;

    private CasesDetailUpPresenter presenter;
    private ImageAdapter adapter;
    private RelativeLayout rel_camera_album;
    private PhotoHelper mPhotoHelper;
    private int currOnclickImage = 0;
    private int position = 0;
    int imagenum = 0;
    private RelativeLayout Rl_all;

    private Handler mHandler = new Handler();
    private boolean isVersion = false;

    @Override
    public void init() {
        initview();

        initdata();

        //时钟初始化
        calendar = Calendar.getInstance();
    }

    private void initdata() {
        this.capturePath = ABFileUtil.getAppTmpPath() + "/TMP.jpg";
        mPhotoHelper = new PhotoHelper(this, capturePath);

        recId = getIntent().getStringExtra("recId");
        presenter = new CasesDetailUpPresenter(this, this);
        if (!Util.isEmpty(recId)) {
            presenter.getcasesdetail(recId);
        }
        adapter = new ImageAdapter(this);
        mGvImg.setIsIntercept(false);
        mGvImg.setAdapter(adapter);
        adapter.addImageSign();
    }

    public void setHandler(Handler handler) {
        mHandler = handler;
    }

    private class ImageAdapter extends PictureGridViewAdapter {

        public ImageAdapter(Context context) {
            super(context);
        }

        @Override
        protected void handleExistImage() {

        }

        @Override
        protected void deleteImage(int position) {
            presenter.deletePic(adapter.getItem(position).getUrl(), position);
        }

        @Override
        protected void addImage() {
            ABAppUtil.hideSoftInput(CasesDetailUpActivity.this);
            //图片添加布局
            rel_camera_album.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (rel_camera_album.getVisibility() == View.VISIBLE) {
                rel_camera_album.setVisibility(View.GONE);
            } else {
                finish();
            }
        }
        return true;
    }


    private void initview() {
        setText(R.id.tv_title, "上传电子病历");
        mEtHospital = (EditText) findViewById(R.id.et_hospital);
        mEtDoctorName = (EditText) findViewById(R.id.et_doctorname);
        mEtJibing = (EditText) findViewById(R.id.et_jibing);
        mEtResult = (EditText) findViewById(R.id.et_result);
        mTvDate = (TextView) findViewById(R.id.tv_date_time);
        mTvFinish = (TextView) findViewById(R.id.tv_finish);
        mTvFinish.setVisibility(View.VISIBLE);
        mTvFinish.setText("保存");
        //医生建议
        mTvSurvey = (TextView) findViewById(R.id.tv_survey);
        mTvMedicine = (TextView) findViewById(R.id.tv_medicine);
        mTvSee = (TextView) findViewById(R.id.tv_see);
        mTvOther = (TextView) findViewById(R.id.tv_other);
        mEtSurevy = (EditText) findViewById(R.id.et_survey);
        mEtMedicine = (EditText) findViewById(R.id.et_medicine);
        mEtSee = (EditText) findViewById(R.id.et_see);
        mEtOther = (EditText) findViewById(R.id.et_other);
        mGvImg = (TagsGridView) findViewById(R.id.gv_image);
        Rl_all = (RelativeLayout) findViewById(R.id.Rl_all);
        rel_camera_album = (RelativeLayout) findViewById(R.id.rel_camera_album);
//        mLlSurevy = (LinearLayout) findViewById(R.id.ll_survey);
//        mLlMedicine = (LinearLayout) findViewById(R.id.ll_medicine);
//        mLlSee = (LinearLayout) findViewById(R.id.ll_see);
//        mLlOther = (LinearLayout) findViewById(R.id.ll_other);
        rel_camera_album.setOnClickListener(this);
        mTvFinish.setOnClickListener(this);
        findViewById(R.id.tv_finish).setOnClickListener(this);
        mTvSurvey.setOnClickListener(this);
        mTvMedicine.setOnClickListener(this);
        mTvSee.setOnClickListener(this);
        mTvOther.setOnClickListener(this);
        findViewById(R.id.btn_camera).setOnClickListener(this);
        findViewById(R.id.btn_album).setOnClickListener(this);
        findViewById(R.id.btn_cancel).setOnClickListener(this);
        findViewById(R.id.ll_time).setOnClickListener(this);
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.ll_time:
                ABAppUtil.hideSoftInput(this);
                getYearMD(mTvDate);
                break;
            case R.id.tv_finish:
                List<Advice> advicelist = new ArrayList<>();
                if (issurvey) {
                    Advice advice = new Advice();
                    advice.setType("1");
                    advice.setContent(mEtSurevy.getText().toString());
                    advicelist.add(advice);
                }
                if (issee) {
                    Advice advice = new Advice();
                    advice.setType("2");
                    advice.setContent(mEtSee.getText().toString());
                    advicelist.add(advice);
                }
                if (ismedcine) {
                    Advice advice = new Advice();
                    advice.setType("3");
                    advice.setContent(mEtMedicine.getText().toString());
                    advicelist.add(advice);
                }
                if (isother) {
                    Advice advice = new Advice();
                    advice.setType("4");
                    advice.setContent(mEtOther.getText().toString());
                    advicelist.add(advice);
                }
                Gson gson = new Gson();
                advices = gson.toJson(advicelist);
                if (adapter.getCount() == 6) { //如果图片有6张
                    if (0 == adapter.getItem(0).getType()) { //如果第一张是添加图片
                        //图片拼接
                        String[] strings = new String[adapter.getCount() - 1];
                        for (int i = 1; i < adapter.getCount(); i++) {
                            strings[i - 1] = adapter.getItem(i).getKey();
                        }
                        pics = gson.toJson(strings);
                    } else {//如果第一张不是添加图片
                        //图片拼接
                        String[] strings = new String[mGvImg.getCount()];
                        for (int i = 0; i < mGvImg.getCount(); i++) {
                            strings[i] = adapter.getItem(i).getKey();
                        }
                        pics = gson.toJson(strings);
                    }
                } else if (adapter.getCount() < 6) {
                    //图片拼接
                    String[] strings = new String[adapter.getCount() - 1];
                    for (int i = 1; i < mGvImg.getCount(); i++) {
                        strings[i - 1] = adapter.getItem(i).getKey();
                    }
                    pics = gson.toJson(strings);
                }


                if (getcasesdata()) {
                    if ("[]".equals(pics)) {
                        pics = "";
                    }
                    if ("[]".equals(advices)) {
                        showToastMessage("请选择医生建议");
                    } else {
                        presenter.uploadCases(hospital, clinicDate, doctorName, descr, result, advices, pics, recId);
                    }
                }

                break;
            case R.id.tv_survey:
                if (issurvey) {//选中
                    issurvey = false;
                    ischeckfalse(mTvSurvey);
                } else {
                    ischecktrue(mTvSurvey);
//                    mEtSurevy.setFocusable(true);
//                    mEtSurevy.setFocusableInTouchMode(true);
//                    mEtSurevy.requestFocus();
                    issurvey = true;
                }
                break;
            case R.id.tv_medicine:
                if (ismedcine) {
                    ismedcine = false;
                    ischeckfalse(mTvMedicine);
                } else {
//                    mEtMedicine.setFocusable(true);
//                    mEtMedicine.setFocusableInTouchMode(true);
//                    mEtMedicine.requestFocus();
                    ismedcine = true;
                    ischecktrue(mTvMedicine);
                }
                break;
            case R.id.tv_see:
                if (issee) {
                    issee = false;
                    ischeckfalse(mTvSee);
                } else {
                    ischecktrue(mTvSee);
//                    mEtSee.setFocusable(true);
//                    mEtSee.setFocusableInTouchMode(true);
//                    mEtSee.requestFocus();
                    issee = true;
                }
                break;
            case R.id.tv_other:
                if (isother) {
                    isother = false;
                    ischeckfalse(mTvOther);
                } else {
//                    mEtOther.setFocusable(true);
//                    mEtOther.setFocusableInTouchMode(true);
//                    mEtOther.requestFocus();
                    isother = true;
                    ischecktrue(mTvOther);

                }
                break;
            case R.id.btn_camera:
                this.rel_camera_album.setVisibility(View.GONE);
                mPhotoHelper.takePhoto();
                break;
            case R.id.btn_album:
                this.rel_camera_album.setVisibility(View.GONE);
                mPhotoHelper.takePictureFromAlbum();

                break;
            case R.id.btn_cancel:
                this.rel_camera_album.setVisibility(View.GONE);
                break;
            case R.id.rel_camera_album:
                this.rel_camera_album.setVisibility(View.GONE);
                break;
        }

    }

    private void ischeckfalse(TextView view) {
        view.setTextColor(Color.parseColor("#444444"));
        view.setBackground(getResources().getDrawable(R.drawable.bg_user_select));
    }

    private void ischecktrue(TextView view) {
        view.setTextColor(Color.parseColor("#ffffff"));
        view.setBackground(getResources().getDrawable(R.drawable.bg_doctor_label_yellow));
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_upload_cases);
    }


    @Override
    public void uploadsucced() {
        showToastMessage("保存成功");
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void uploadfail() {
        showToastMessage("保存失败");
    }

    @Override
    public void getcasesdetail(CasesDetail casesDetail, List<Quslist> quslists, List<Advice> advices, List<ImageInfo> imageInfos) {
        if (casesDetail != null) {
            mEtHospital.setText(casesDetail.getHosName());
            mTvDate.setText(casesDetail.getClinicDate());
            mEtDoctorName.setText(casesDetail.getDctName());
            mEtJibing.setText(casesDetail.getDescr());
            mEtResult.setText(casesDetail.getResult());
        }
        if (!Util.isEmpty(advices)) {
            for (int i = 0; i < advices.size(); i++) {
                Advice advice = advices.get(i);
                if ("1".equals(advice.getType())) {
                    issurvey = true;
                    ischecktrue(mTvSurvey);
                    mEtSurevy.setText(advice.getContent());
                } else if ("2".equals(advice.getType())) {
                    issee = true;
                    ischecktrue(mTvSee);
                    mEtSee.setText(advice.getContent());
                } else if ("3".equals(advice.getType())) {
                    ismedcine = true;
                    ischecktrue(mTvMedicine);
                    mEtMedicine.setText(advice.getContent());
                } else if ("4".equals(advice.getType())) {
                    isother = true;
                    ischecktrue(mTvOther);
                    mEtOther.setText(advice.getContent());
                }
            }
        }
        if (!Util.isEmpty(imageInfos)) {
            if (imageInfos.size() == 6) {
                adapter.removeData(0);
                isVersion = true;
            }
            adapter.addData(imageInfos);
        }
    }

    @Override
    public void getcasesdetailfail() {
        showToastMessage("获取失败");
    }


    @Override
    public void addImage(ImageInfo imageInfo) {
        if (adapter.getData().size() < ConstantValue.MAX_PICTURE_NUMBER) {
            this.adapter.addData(imageInfo);
        } else {
            this.adapter.addData(imageInfo);
            this.adapter.removeData(0);
            isVersion = true;
        }
        this.adapter.notifyDataSetChanged();
    }

    @Override
    public void deletesucced(int position) {
        if (isVersion) {
            this.adapter.removeData(position);
            adapter.addImageSign();
            isVersion = false;
        } else {
            this.adapter.removeData(position);
        }


    }

    @Override
    public void deletefail() {
    }


    public boolean getcasesdata() {
        hospital = mEtHospital.getText().toString();
        clinicDate = mTvDate.getText().toString();
        doctorName = mEtDoctorName.getText().toString();
        descr = mEtJibing.getText().toString();
        result = mEtResult.getText().toString();
        if (Util.isEmpty(hospital)) {
            showToastMessage("请输入就诊医院");
            return false;
        } else if (Util.isEmpty(clinicDate)) {
            showToastMessage("请选择就诊日期");
            return false;
        } else if (Util.isEmpty(doctorName)) {
            showToastMessage("请输入医生姓名");
            return false;
        } else if (Util.isEmpty(descr)) {
            showToastMessage("请输入您所患的疾病");
            return false;
        } else if (Util.isEmpty(result)) {
            showToastMessage("请输入诊断结果");
            return false;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPhotoHelper.TO_CAMEIA && resultCode == RESULT_OK) {//来自系统相机的返回
            mPhotoHelper.startPhotoZoom(Uri.fromFile(new File(capturePath)));
        } else if (requestCode == mPhotoHelper.TO_PHOTO && resultCode == RESULT_OK && data != null) {//来自系统相册的返回
            Uri uri = data.getData();
            mPhotoHelper.startPhotoZoom(uri);
        } else if (requestCode == ConstantValue.TO_OPENIMAGE && resultCode == ConstantValue.RESULT_DELETE) {//已经删除了照片
            this.adapter.removeData(this.currOnclickImage);
        } else if (requestCode == mPhotoHelper.TO_ZOOM_PHOTO && data != null) {//裁剪完成后
            this.presenter.updateImageFromUri(capturePath);
        }
    }

    /**********************************************
     * 日期滚轴后期封装
     *****************************************************/
    private String selectDate, selectTime;
    private Calendar calendar;
    private MyDatePicker tp_test;
    private TextView tv_ok, tv_cancel;    //确定、取消button
    private PopupWindow pw;
    private int dateYear, dateMonth, dateDay;
    //选择时间与当前时间，用于判断用户选择的是否是以前的时间
    private int currentHour, currentMinute, currentDay, selectHour, selectMinute, selectDay;

    protected void getYearMD(final TextView mTvDate) {
        View view = View.inflate(CasesDetailUpActivity.this, R.layout.dialog_select_time, null);
        selectDate = calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH) + "-";
        //选择时间与当前时间的初始化，用于判断用户选择的是否是以前的时间，如果是，弹出toss提示不能选择过去的时间
        selectDay = currentDay = calendar.get(Calendar.DAY_OF_MONTH);
        selectMinute = currentMinute = calendar.get(Calendar.MINUTE);
        selectHour = currentHour = calendar.get(Calendar.HOUR_OF_DAY);

        selectTime = currentHour + "点" + ((currentMinute < 10) ? ("0" + currentMinute) : currentMinute) + "分";
        tp_test = (MyDatePicker) view.findViewById(R.id.tp_test);
        tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        tv_cancel = (TextView) view.findViewById(R.id.tv_cancel);
        //设置滑动改变监听器
//        dp_test.setOnChangeListener(dp_onchanghelistener);
        tp_test.setOnChangeListener(tp_onchanghelistener);
        pw = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
//				//设置这2个使得点击pop以外区域可以去除pop
//				pw.setOutsideTouchable(true);
//				pw.setBackgroundDrawable(new BitmapDrawable());

        //出现在布局底端
        pw.showAtLocation(Rl_all, 0, 0, Gravity.END);

        //点击确定
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (selectDay == currentDay) {    //在当前日期情况下可能出现选中过去时间的情况
                    if (selectHour < currentHour) {
                        MyToast.DefaultmakeText(getApplicationContext(), "不能选择过去的时间\n        请重新选择", 0);
                    } else if ((selectHour == currentHour) && (selectMinute < currentMinute)) {
                        MyToast.DefaultmakeText(getApplicationContext(), "不能选择过去的时间\n        请重新选择", 0);
                    } else {
                        Calendar now = Calendar.getInstance();
                        if (dateYear > now.get(Calendar.YEAR)) {
                            showToastMessage("您只能选择今天之前的日期作为就诊日期");
                        } else {
                            if (dateYear == now.get(Calendar.YEAR)) {
                                if (dateMonth > (now.get(Calendar.MONTH) + 1)) {
                                    showToastMessage("您只能选择今天之前的日期作为就诊日期");
                                } else {
                                    if (dateMonth == (now.get(Calendar.MONTH) + 1)) {
                                        if (dateDay > now.get(Calendar.DAY_OF_MONTH)) {
                                            showToastMessage("您只能选择今天之前的日期作为就诊日期");
                                        } else {
                                            mTvDate.setText(selectDate);
                                        }
                                    } else {
                                        mTvDate.setText(selectDate);
                                    }
                                }
                            } else {
                                mTvDate.setText(selectDate);
                            }
                        }
                        pw.dismiss();
                    }
                } else {
                    mTvDate.setText(selectDate);
                    pw.dismiss();
                }
            }
        });

        //点击取消
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                pw.dismiss();
            }
        });
    }

    MyDatePicker.OnChangeListener tp_onchanghelistener = new MyDatePicker.OnChangeListener() {
        @Override
        public void onChange(int year, int month, int day, int day_of_week) {
            dateYear = year;
            dateMonth = month;
            dateDay = day;
            selectDate = year + "-" + month + "-" + day;

        }

    };
}
